# -*- coding:utf-8 -*-
import json
import os
import time
import sqlite3
import psutil

last_down = 0
last_up = 0

info = {}


def sqlexec(sql, type=False):
    db = sqlite3.connect(os.path.abspath('net.db'))
    start = db.cursor()
    result = start.execute(sql)
    if type:
        result = result.fetchall()

    start.close()
    db.commit()
    return result


def refresh():
    global last_down, last_up, info
    net_list = psutil.net_io_counters(pernic=True)
    all = 0
    now = 0
    for i in net_list:
        n = net_list[i]
        all = n.bytes_sent + all
        now = n.bytes_recv + now
        pass
    up = round((all - last_up) / 1024, 2)
    down = round((now - last_down) / 1024, 2)
    if last_down != 0:
        # print(f"上传：{up}=>下载：{down}")
        now_time = int(time.time())
        sql = f"DELETE FROM net WHERE time < {(now_time - 300)}"
        sqlexec(sql)
        sqlexec(f"INSERT INTO net ('up','down','time') values ({up},{down},{now_time})")
        pass
    last_up = all
    last_down = now
    dt = {"up": up, 'down': down}
    info['net'] = dt
    return dt


def bytes_to_gb(bytes):
    return float("%.2f" % (bytes / 1024 / 1024 / 1024))


# 磁盘占用
def disk():
    global info
    diskinfo = psutil.disk_usage("/")
    _info = {
        "total": bytes_to_gb(diskinfo.total),
        "used": bytes_to_gb(diskinfo.used),
        'free': bytes_to_gb(diskinfo.free),
        "percent": diskinfo.percent
    }
    info['disk'] = _info
    return _info


def mem():
    global info
    meminfo = psutil.virtual_memory()
    _info = {"total": bytes_to_gb(meminfo.total), "used": bytes_to_gb(meminfo.used),
             'free': bytes_to_gb(meminfo.total - meminfo.used), "percent": meminfo.percent}
    now_time = int(time.time())
    sql = f"DELETE FROM mem WHERE time < {(now_time - 300)}"
    sqlexec(sql)
    sqlmem = f"INSERT INTO mem ('used','free','total','time') values ({_info['used']},{_info['free']},{_info['total']},{now_time})"
    sqlexec(sqlmem)
    info['mem'] = _info
    return _info


def cpus():
    global info
    cpu = psutil.cpu_count()
    _info = {'percent': psutil.cpu_percent(), 'count': cpu}
    info['cpu'] = _info
    return _info


def getinfo():
    global info
    return info


def start():
    print('已启动')
    while True:
        refresh()
        disk()
        mem()
        cpus()
        time.sleep(1)


if '__main__' == __name__:
    print('已启动')
    f = open('net.pid', 'w')
    f.write(str(os.getpid()))
    f.close()
    while True:
        os.system("clear")
        print(refresh())
        print(disk())
        print(mem())
        print(cpus())
        print("---------")
        time.sleep(1)
